package com.wsd.bookkeeping.service.impl;

import com.wsd.bookkeeping.entity.Right;
import com.wsd.bookkeeping.form.PermissionForm;
import com.wsd.bookkeeping.mapper.AccountMapper;
import com.wsd.bookkeeping.mapper.RightMapper;
import com.wsd.bookkeeping.service.RightService;
import com.wsd.bookkeeping.vo.UserRightListVO;
import com.wsd.common.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class RightServiceImpl implements RightService {

    @Resource
    private RightMapper rightMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AccountMapper accountMapper;

    @Override
    public Boolean saveOrUpdateUserPermission(PermissionForm form) {
        return rightMapper.saveOrUpdateUserPermission(form);
    }

    @Override
    public List<Right> getRightList() {
        return rightMapper.queryRightList();
    }

    @Override
    public UserRightListVO getRightListById(Integer userId, Integer bookId) {
        return rightMapper.queryRightListByUserId(userId, bookId);
    }

    @Override
    public Map<String, Object> getUserInfo(Integer userId, Integer bookId) throws InterruptedException {
        Map<String, Object> userInfoMap = new HashMap<>();
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CountDownLatch countDownLatch = new CountDownLatch(3);

        // 用户信息
        executorService.execute(() -> {
            userInfoMap.put("userInfo", userMapper.getUserInfo(userId));
            countDownLatch.countDown();
        });

        // 用户记账信息
        executorService.execute(() -> {
            userInfoMap.put("recordInfo", accountMapper.queryUserCurrentRecordInfo(userId, bookId));
            countDownLatch.countDown();
        });

        // 用户权限信息
        executorService.execute(() -> {
            UserRightListVO userRightListVO = rightMapper.queryRightListByUserId(userId, bookId);
            userInfoMap.put("permissions", userRightListVO == null ? new ArrayList<>() : userRightListVO.getRightList());
            countDownLatch.countDown();
        });

        countDownLatch.await();

        return userInfoMap;
    }
}
